package com.stu.config.shiro;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 1、配置Reaml——自定义Realm
 * 2、配置SecurityManager
 * 3、配置ShiroFilterFactoryBean
 */
@Configuration
public class ShiroConfig {
    @Bean
    public Realm realm(){
        return new MyRealm();
    }
    @Bean
    public SecurityManager securityManager(Realm realm){
        return new DefaultWebSecurityManager(realm);
    }
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager){
        ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
        factoryBean.setSecurityManager(securityManager);//设置安全管理器

        //定义过滤链——key是资源、value是权限
        Map<String,String> filterMap = new LinkedHashMap<>();
        filterMap.put("/user/toSelect","anon");
        filterMap.put("/user/toAdd","authc");
        filterMap.put("/user/toDelete","roles[user]");
        filterMap.put("/user/toUpdate","perms[user:update]");

        factoryBean.setFilterChainDefinitionMap(filterMap);//设置过滤链
        factoryBean.setLoginUrl("/toLogin");//设置登录页面。如果被authc拦截（用户未认证）则跳转到该页面。如果不设置该选项则页面报异常。
        factoryBean.setUnauthorizedUrl("/unAuthr");//设置未授权页面。如果被perms拦截（用户未授权）则跳转到该页面。如果不设置该选项则页面报异常。

        return factoryBean;
    }

    //配置bean——thymeleaf的shiro属性相关
    @Bean
    public ShiroDialect shiroDialect(){return new ShiroDialect();}
}
